package com.cj.tool.http.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.os.Handler;
import android.os.Message;

/**
 * 自定义一个Dilaog 便于控制返回键
 *
 * @author zengyi
 * create at 2017/1/19 14:31
 */
public class ProgressDialogHandler extends Handler {

	public static final int SHOW_PROGRESS_DIALOG = 1;
	public static final int DISMISS_PROGRESS_DIALOG = 2;
	private Dialog mDialog;
	private Activity mActivity;
	private boolean cancelable;
	private ProgressCancelListener mProgressCancelListener;

	public ProgressDialogHandler(Activity activity, ProgressCancelListener mProgressCancelListener,
                                 boolean cancelable) {
		super();
		this.mActivity = activity;
		this.mProgressCancelListener = mProgressCancelListener;
		this.cancelable = cancelable;
	}

	private void initProgressDialog() {
		try {
			if (mActivity.isFinishing() || mActivity == null) return;
			if (mDialog == null) {
				mDialog = DialogUtils.createLoadingDialog(mActivity,"");
				mDialog.setCancelable(cancelable);
				if (cancelable) {
					if (mProgressCancelListener != null) {
						mDialog.setOnCancelListener(dialogInterface -> mProgressCancelListener.onCancelProgress());
					}
				}
				if (!mDialog.isShowing()) {
					mDialog.show();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void dismissProgressDialog() {
		try {
			if (mDialog != null) {
				mDialog.dismiss();
				mDialog = null;
			}
			if (mActivity != null) {
				mActivity = null;
			}
			if (mProgressCancelListener != null) {
				mProgressCancelListener = null;
			}
			removeCallbacksAndMessages(null);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void handleMessage(Message msg) {
		switch (msg.what) {
			case SHOW_PROGRESS_DIALOG:
				initProgressDialog();
				break;
			case DISMISS_PROGRESS_DIALOG:
				dismissProgressDialog();
				break;
		}
	}

}